var express = require("express");
var expressWebSocket = require("express-ws");
var ffmpeg = require("fluent-ffmpeg");
var mysql = require("mysql"); // 引入mysql模块
ffmpeg.setFfmpegPath("/usr/bin/ffmpeg");
var webSocketStream = require("websocket-stream/stream");
var WebSocket = require("websocket-stream");
const cors = require("cors");

// 配置数据库连接
var dbConfig = {
    host: "10.112.89.161",  // 数据库主机地址
    user: "cloud",          // 数据库用户名
    password: "123456",     // 数据库密码
    database: "test"        // 数据库名称
};

// 创建数据库连接池
var pool = mysql.createPool(dbConfig);

function fetchUserData(tableName, callback) {
    const query = `SELECT * FROM ${tableName}`;
    pool.query(query, function (error, results) {
        if (error) {
            console.error("Error fetching data: ", error);
            callback(error, null);
        } else {
            console.log("Data retrieved from table " + tableName);
            callback(null, results);
        }
    });
}

function localServer() {
    let app = express();
    app.use(cors()); // 允许所有来源的请求
    app.use(express.static(__dirname));
    expressWebSocket(app, null, {
        perMessageDeflate: true
    });

    // 定义一个路由来获取user表的数据
    app.get("/getResult", function (req, res) {
        const name = req.query.name.replace(/-/g, "");
        fetchUserData(name, function (error, data) {
            if (error) {
                res.status(500).send("Error retrieving data");
            } else {
                res.json(data);
            }
        });
    });

    app.ws("/rtsp/:id/", rtspRequestHandle);
    app.listen(2333);
    console.log("Express server is listening on port 2333");
}

function rtspRequestHandle(ws, req) {
    console.log("RTSP request handle");
    const stream = webSocketStream(ws, {
        binary: true,
        browserBufferTimeout: 1000000
    }, {
        browserBufferTimeout: 1000000
    });

    let url = req.query.url;
    console.log("RTSP URL:", url);
    console.log("RTSP Params:", req.params);

    try {
        ffmpeg(url)
            .addInputOption("-rtsp_transport", "tcp", "-buffer_size", "4096k", "-analyzeduration", "0", "-probesize", "100M", "-flags", "low_delay")
            .outputOptions("-fflags nobuffer")
            .on("start", function () {
                console.log(url, "Stream started.");
            })
            .on("codecData", function () {
                console.log(url, "Stream codec data received.");
            })
            .on("error", function (err) {
                console.log(url, "An error occurred: ", err.message);
            })
            .on("end", function () {
                console.log(url, "Stream ended.");
            })
            .format("flv")
            .videoCodec("copy")
            .noAudio()
            .pipe(stream, { end: true });
    } catch (error) {
        console.log(error);
    }
}

localServer();
